using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using KissEcs;
using KBEngine;
using ThinkingData.Analytics;

/// <summary>
/// 之前项目中使用的新手引导控制器，可以参考，但不能直接使用
/// </summary>
public class GuideMgr : Singleton<GuideMgr>
{
    public List<GuideData> list = new();
    public Dictionary<int, GuideStepData> dict = new();
    public List<int> waitExecutedList = new();

    public int guidingId = 0;
    public int stepIdx = 0;
    public bool isGuiding = false;//正在引导
    public bool checkCondition = false;

    private Transform layer;
    private bool isFirst = true;
    public GameObject tutorial;

    public bool startGuide = false;

    private void Start()
    {
        layer = GameObject.Find("Canvas/TutorialLayer").transform;
        EventManager.Register<int>("CompleteStep", this, CompletedStep);
        EventManager.Register("ExitGame", this, EndGuide);
        EventManager.Register<INT32_ARRAY>("GuideStep", this, UpdateGuideProcess);
    }

    private void Update()
    {
        //获得服务器下发数据
        if (startGuide)
        {
            //保持服务器连线
            if (!Global.IsDisconnect)
            {
                //是否开启引导
                if (isGuiding)
                {
                    //是否开启条件检测
                    if (checkCondition)
                    {
                        if (CheckCondition(stepIdx) && (guidingId == 1 || !ChainEventHanding.Instance.isUnlock))//满足执行条件
                        {
                            //执行分步骤
                            ExecuteGuideStep();
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 读表获取引导信息
    /// </summary>
    public void InitGuideData()
    {
        list.Clear();
        dict.Clear();
        var tables = World.GetModel<cfg.Tables>().TbGuide;
        foreach (var item in tables.DataList)
        {
            list.Add(new() { id = item.Id, skip = item.Skip, condition = item.Condition, parameter = item.Parameter, priority = item.Priority, startIndex = item.StartIndex, stepList = item.Step, name = item.Name });
        }

        foreach (var item in World.GetModel<cfg.Tables>().TbGuideStep.DataList)
        {
            GuideStepData step = new GuideStepData() { id = item.Id, type = item.Type, content = item.Content, pause = item.Pause, action = item.Action, parameter = item.Parameter, nextStep = item.NextStep };
            dict.Add(item.Id, step);
        }

        //Debug.Log("新手引导初始化完毕");
    }

    private void UpdateGuideProcess(INT32_ARRAY lst)
    {
        foreach (var num in lst)
        {
            foreach (var item in list)
            {
                if (item.id == num)
                {
                    item.state = 1;
                }
            }
        }
        //获取到服务器下发的数据之后置true
        startGuide = true;
        DetermineExecutableGuide();
    }

    /// <summary>
    /// 启动引导
    /// </summary>
    public void StartGuide()
    {
        if (waitExecutedList.Count == 0)
        {
            return;
        }
        //引导排序
        waitExecutedList = waitExecutedList.OrderBy(x => x).ToList();

        guidingId = waitExecutedList[0];
        ExecuteGuide(guidingId);
    }

    [ContextMenu("DetermineExecutableGuide")]
    /// <summary>
    /// 判断可执行的引导
    /// </summary>
    public void DetermineExecutableGuide()
    {
        if (ChainEventHanding.Instance.lists.Count != 0)
        {
            return;
        }

        foreach (var item in list)
        {
            if (item.state == 0 && !item.inList)
            {
                if (GuideIsExecutable(item.condition, item.parameter))
                {
                    Debug.Log($"加入引导:{item.id}");
                    waitExecutedList.Add(item.id);
                    item.inList = true;
                }
            }
        }

        if (!isGuiding)
        {
            StartGuide();
        }
    }

    public bool GuideIsExecutable(cfg.guide.Condition condition, int value)
    {
        bool state = false;
        switch (condition)
        {
            case cfg.guide.Condition.FIRSTGAME:
                foreach (var item in list)
                {
                    if (item.id == 1 && item.state == 0)
                    {
                        state = true;
                    }
                }
                break;
            case cfg.guide.Condition.UNLOCK_FUNCTION:
                var avatarOther = Global.Player.AvatarOther;
                if (avatarOther.functionUnlockStep.Contains(value))
                {
                    state = true;
                }
                break;
            case cfg.guide.Condition.COMPLETE_GUIDE:
                foreach (var item in list)
                {
                    if (item.id == value && item.state == 1)
                    {
                        state = true;
                    }
                }
                break;
            case cfg.guide.Condition.MEET_CONDITION:
                //特殊事件
                break;
            default:
                break;
        }
        return state;
    }

    /// <summary>
    /// 执行引导
    /// </summary>
    public void ExecuteGuide(int id)
    {
        foreach (var item in list)
        {
            if (item.id == id)
            {
                stepIdx = item.startIndex;
            }
        }

        LoadTutorial(true);
    }

    /// <summary>
    /// 检测执行条件
    /// </summary>
    /// <returns></returns>
    private bool CheckCondition(int idx)
    {
        bool state = false;
        switch (dict[idx].action)
        {
            case cfg.guideStep.Action.START:
                if (guidingId == 1)
                {
                    state = true;
                }
                if (FindMainView() && !CollectGameDataSystem.HasUnFinishedBattle())
                {
                    state = true;
                }
                break;
            case cfg.guideStep.Action.DROP:
                //特殊条件
                break;
            case cfg.guideStep.Action.SHOW_UI:
                    state = Tutorial.Instance.ComputeCondition(idx);
                break;
            case cfg.guideStep.Action.COMPLETE_LAST_STEP:
                state = true;
                break;
        }
        return state;
    }

    public void ExecuteGuideStep()
    {
        //关闭条件检测引导
        checkCondition = false;

        Tutorial.Instance.InitLogicAdd(stepIdx);
        Tutorial.Instance.isStart = true;
        foreach (var item in list)
        {
            if (item.id == guidingId)
            {
                Tutorial.Instance.canSkip = item.skip == 1;
            }
        }
    }

    public void CompletedGuide(int id)
    {
        LoadTutorial(false);
        foreach (var item in list)
        {
            if (item.id == id)
            {
                item.state = 1;
                waitExecutedList.Remove(item.id);
                //ToSave(id);
                int tutorialStep = id;
                Global.Player.AvatarOther.PushTutorialStep(tutorialStep);
            }
        }
        isGuiding = false;
        checkCondition = false;
        stepIdx = 0;
        guidingId = 0;
        DetermineExecutableGuide();
        if (waitExecutedList.Count != 0)
        {
            StartGuide();
        }
    }

    public void CompletedStep(int id)
    {
        if (id == stepIdx)
        {
            dict[id].isCompleted = true;
            stepIdx = dict[id].nextStep;

            if (stepIdx == 0)
            {
                CompletedGuide(guidingId);
                return;
            }
            checkCondition = true;
        }
    }

    private void EndGuide()
    {
        if (guidingId == 1 && isGuiding)
        {
            //stepIdx = 1005;
            //CompletedStep(1005);
            CompletedGuide(1);
            Debug.Log("完成引导1");
        }
    }

    public void SkipGuide()
    {
        Debug.Log($"跳过引导{guidingId}");
        CompletedGuide(guidingId);
    }

    /// <summary>
    /// 加载新手引导模块
    /// </summary>
    /// <param name="state"></param>
    private async void LoadTutorial(bool state)
    {

        if (state)
        {
            if (isFirst)
            {
                isFirst = false;
                var cell = await AssetLoader.Load<GameObject>(this, "Tutorial");
                tutorial = Instantiate(cell, layer);
            }
            if (tutorial != null)
            {
                var canvasGroup = tutorial.GetComponent<CanvasGroup>();
                tutorial.GetComponent<IUI>().OnShow();
                canvasGroup.alpha = 1.0f;
                canvasGroup.blocksRaycasts = true;

                if (stepIdx == 1 && Global.Player.AvatarOther.chapterId != 1)
                {
                    if (guidingId == 1 && isGuiding)
                    {
                        CompletedGuide(1);
                        Debug.Log("完成引导1");
                    }
                }

                isGuiding = true;
                //开启条件检测
                checkCondition = true;
            }
        }
        else
        {
            var canvasGroup = tutorial.GetComponent<CanvasGroup>();
            tutorial.GetComponent<IUI>().OnHide();
            canvasGroup.alpha = 0.0f;
            canvasGroup.blocksRaycasts = false;
        }
    }

    public bool FindMainView()
    {
        bool active = false;
        var main = GameObject.Find("Canvas/UILayer/Main(Clone)");
        var bar = GameObject.Find("Canvas/UILayer/Bar(Clone)");
        var recover = GameObject.Find("Canvas/UILayer/RecoverGameUI(Clone)");
        var journey = GameObject.Find("Canvas/UILayer/Journey(Clone)");
        var task = GameObject.Find("Canvas/UILayer/Task(Clone)");
        var activeTask = GameObject.Find("Canvas/UILayer/NotEnoughFrequency(Clone)");
        var mail = GameObject.Find("Canvas/UILayer/NotEnoughItem(Clone)");
        var dailyReward = GameObject.Find("Canvas/UILayer/DailyReward(Clone)");

        if (recover != null)
        {
            var group = recover.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }

        if (journey != null)
        {
            var group = task.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }

        if (task != null)
        {
            var group = task.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }

        if (activeTask != null)
        {
            var group = activeTask.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }

        if (mail != null)
        {
            var group = mail.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }
        if (dailyReward != null)
        {
            var group = dailyReward.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
                return false;
        }

        if (main != null && bar != null)
        {
            //UnityEngine.Debug.Log("main 和 bar 都加载到了");
            var group = main.GetComponent<CanvasGroup>();
            var barGroup = bar.GetComponent<CanvasGroup>();
            active = group.alpha == 1 && barGroup.alpha == 1;

        }
        return active;
    }
}

[Serializable]
public class GuideData
{
    public int id;//引导id
    public int skip;//是否可以跳过
    public cfg.guide.Condition condition;//触发引导条件
    public int parameter;//引导参数
    public int priority;//优先级
    public int startIndex;//起始节点
    public List<int> stepList;
    public int state = 0;//引导完成情况-0未完成1已完成
    public bool inList = false;//是否进入等待执行列表
    public string name;
}

public class GuideStepData
{
    public int id;//分步id
    public int type;//引导类型-1指向2弹窗
    public string content;//弹窗内容
    public int pause;//是否暂停游戏-0不暂停1暂停
    public cfg.guideStep.Action action;//事件类型(步骤触发条件)
    public cfg.guideStep.Parameter parameter;//遮罩类型，0无1圆形2矩形
    public int nextStep;//下一步Id
    public bool isCompleted = false;
}

public class EquipInfo
{
    public int tableId;
    public int quality;
}

